<template>
	<div class="app_auth">
		<!-- 客户信息 -->
		<div class="auth_user" v-if="custInfo">
			<div class="user_left">
				<VanImage
					class="user_avatar"
					:src="custInfo.avatar"
					:error-icon="require('@IMG/icon_cust_avatar.png')"
					:loading-icon="require('@IMG/icon_cust_avatar.png')"
				/>
				<i
					class="user_certified"
					:class="custInfo.certified ? 'has_certified' : 'un_certified'"
				>
					{{ custInfo.certified ? '已认证' : '未认证' }}
				</i>
			</div>
			<div class="user_right">
				<div class="user_name">
					{{ custInfo.certified ? custInfo.name : custInfo.nickName }}
				</div>
				<div class="user_corp" :class="{is_qw: custInfo.type === '2'}">
					{{ custInfo.type === '2' ? custInfo.corpName : '微信' }}
				</div>
			</div>
		</div>
		<!-- 客户手机号 -->
		<div class="auth_cust">
			<div class="cust_title">客户手机号</div>
			<VanField
				class="cust_phone"
				v-model="custPhone"
				type="tel"
				center
				clearable
				clear-trigger="always"
				placeholder="请输入"
				maxlength="11"
				:border="false"
				:formatter="(str) => str.replace(/[^0-9]/g, '')"
				@clear="onClearCustPhone"
			/>
			<div class="cust_tips">我们将根据填写的手机号查询该客户信息</div>
		</div>
		<!-- 客户经理手机号 -->
		<div class="auth_manager">
			<div class="manager_title">客户经理手机号</div>
			<VanField
				class="manager_phone"
				v-model="managerPhone"
				type="tel"
				center
				clearable
				clear-trigger="always"
				placeholder="请输入"
				maxlength="11"
				:disabled="isReservedPhone"
				:border="false"
				:formatter="(str) => isReservedPhone ? str : str.replace(/[^0-9]/g, '')"
				@clear="onClearManagerPhone"
			/>
			<!-- TODO:验证码功能暂时不做 -->
			<!-- <div class="manager_title">验证码</div>
			<VanField
				class="auth_sms"
				v-model="sms"
				type="number"
				center
				clearable
				placeholder="请输入"
				maxlength="6"
				:border="false"
				:formatter="(str) => str.replace(/[^0-9]/g, '')"
			>
				<template #button>
					<span
						v-if="[0, 2].includes(smsBtnStatus)"
						class="sms_btn"
						:class="{disabled : !managerPhone.trim() || (!isReservedPhone && !validPhone(managerPhone))}"
						@click="onGetSms"
						>{{ smsBtnStatus === 2 ? '重新获取' : '获取验证码' }}</span
					>
					<VanCountDown
						class="sms_time"
						v-else
						:time="60000"
						@finish="smsBtnStatus = 2"
					>
						<template #default="timeData">
							<i>{{ parseInt(timeData.total/1000) }}</i>
							秒后重新发送
						</template>
					</VanCountDown>
				</template>
			</VanField> -->
		</div>
		<VanButton class="btn_auth" color="#ED3636" @click="onAuth" block
			>完成认证</VanButton
		>
		<VanButton
			v-if="contactId"
			class="btn_list"
			color="#ED3636"
			block
			plain
			hairline
			@click="onJumpList"
			>全部客户</VanButton
		>
	</div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import {
	Field as VanField,
	CountDown as VanCountDown,
	showToast,
	closeToast,
	showLoadingToast,
	showDialog,
} from 'vant'
import {
	GetCustDetail,
	GetLatestPhone,
	VerificationCode,
	CustAuth,
} from '@/api'

// 客户id
const custId = bjsdk.query('custId')
// 通过授权获取的客户id
const contactId = bjsdk.query('contactId')

// 跳转列表页
const onJumpList = () => bjsdk.goTo('/list')

/**
 * <START>手机号及验证码
 */
const custPhone = ref('')
const managerPhone = ref('')
const isReservedPhone = ref(false) // 是否为预留的客户经理手机号
const validPhone = (phone) => /^1[3456789][0-9]{9}$/.test(phone)
const onClearCustPhone = async () => {
	custPhone.value = ''
	document.querySelector('.cust_phone input').focus()
}
const onClearManagerPhone = async () => {
	managerPhone.value = ''
	isReservedPhone.value = false
	await nextTick()
	document.querySelector('.manager_phone input').focus()
}

const sms = ref('')
const smsBtnStatus = ref(0) // 验证码按钮状态 0:展示获取验证码 1:展示倒计时 2:展示重新获取
const smsAvailTime = ref(60000) // 验证码有效时间，用于倒计时
// 获取验证码
const onGetSms = async () => {
	if (smsBtnStatus.value === 1) {
		return
	}
	if (!managerPhone.value.trim()) {
		showToast('请输入客户经理手机号')
		return
	}
	if (!isReservedPhone.value && !validPhone(managerPhone.value)) {
		showToast('客户经理手机号码错误，请重新输入')
		return
	}
	showLoadingToast()
	const phone = isReservedPhone.value ? '' : managerPhone.value
	const {
		code,
		msg,
		data = {},
	} = await VerificationCode({
		phone,
	}).catch(() => ({}))
	if (code !== 200) {
		const message = msg || '获取验证码失败，请稍后重试'
		// if (code === 1607) {
		// 	closeToast()
		// 	 ({
		// 		title: '认证失败',
		// 		message,
		// 		confirmButtonText: '重新输入',
		// 		confirmButtonColor: 'var(--mainTextColor)',
		// 	})
		// 	return
		// }
		showToast(message)
		return
	}
	closeToast()
	sms.value = ''
	smsBtnStatus.value = 1
	smsAvailTime.value = data?.vCodeAvailSeconds * 1000 || 60000
}
// 认证
const onAuth = async () => {
	if (!custPhone.value.trim()) {
		showToast('请输入客户手机号')
		return
	}
	if (!validPhone(custPhone.value)) {
		showToast('客户手机号码错误，请重新输入')
		return
	}
	if (!managerPhone.value.trim()) {
		showToast('请输入客户经理手机号')
		return
	}
	if (!isReservedPhone.value && !validPhone(managerPhone.value)) {
		showToast('客户经理手机号码错误，请重新输入')
		return
	}
	// TODO:验证码功能暂时不做
	// if (!sms.value.trim()) {
	// 	showToast('请输入手机验证码')
	// 	return
	// }
	// if (!/^[0-9]{4,6}$/.test(sms.value)) {
	// 	showToast('手机验证码错误，请重新输入')
	// 	return
	// }
	showLoadingToast()
	const custManagePhone = isReservedPhone.value ? '' : managerPhone.value
	const contactUserId = custId || contactId
	const { code, msg } = await CustAuth({
		custPhone: custPhone.value,
		custManagePhone,
		// TODO:验证码功能暂时不做
		// code: sms.value,
		contactUserId,
	}).catch(() => ({}))
	if (code !== 200) {
		const message = msg || '认证失败，请稍后重试'
		if (code === 1607) {
			closeToast()
			showDialog({
				title: '认证失败',
				message,
				confirmButtonText: '重新输入',
				confirmButtonColor: '#ed3636',
				className: '__auth_dialog__',
			})
			return
		}
		showToast(message)
		return
	}
	showToast({
		message: '认证成功',
		icon: 'passed',
	})
	setTimeout(() => {
		bjsdk.goTo('/detail', {
			append: {
				[contactId ? 'contactId' : 'custId']: contactUserId,
			},
			replace: true,
		})
	}, 300)
}

// 获取用户信息
const custInfo = ref(null)
const getDetail = async () => {
	showLoadingToast()
	const contactUserId = custId || contactId
	const { data: detailData } = await GetCustDetail({
		contactUserId,
	}).catch(() => ({}))
	const { data: phoneData } = await GetLatestPhone().catch(() => {})
	custInfo.value = detailData
	if (phoneData) {
		isReservedPhone.value = true
		managerPhone.value = phoneData
	}
	closeToast()
}
getDetail()
</script>

<style lang="less" scoped>
@import '~@CSS/share.less';
.app_auth {
	margin: 0 30px 20px;
	.auth_user {
		display: flex;
		margin: 20px 0 0;
		padding: 30px;
		border-radius: 12px;
		background: #fff;
		.user_left {
			position: relative;
			width: 92px;
			height: 92px;
			.user_avatar {
				width: 92px;
				height: 92px;
				border-radius: 46px;
				overflow: hidden;
				--van-image-loading-icon-size: 92px;
				--van-image-error-icon-size: 92px;
			}
			.user_certified {
				position: absolute;
				left: 2px;
				top: 68px;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 88px;
				height: 32px;
				border-radius: 16px;
				font-weight: 500;
				font-size: 19px;
				background: linear-gradient(166deg, #f6e6ce 0%, #f5d1b3 100%);
				color: #814223;
			}
		}
		.user_right {
			flex: 1;
			margin: 0 0 0 24px;
			.user_name {
				font-weight: 500;
				font-size: 32px;
				color: #333;
				line-height: 44px;
			}
			.user_corp {
				margin: 10px 0 0;
				color: #48aa00;
				font-size: 22px;
				line-height: 32px;
				&::before {
					content: '@';
				}
				&.is_qw {
					color: #f57526;
				}
			}
		}
	}
	.van-field {
		padding: 30px 0;
		font-size: 30px;
		line-height: 42px;
		.half_border_b();
		:deep(.van-field__value) {
			input {
				color: #333;
				&::placeholder {
					color: #ccc;
					font-size: 28px;
				}
			}
			.van-field__clear {
				color: #999;
				font-size: 36px;
			}
		}
	}
	.auth_cust {
		margin: 20px 0 0;
		padding: 30px 30px;
		border-radius: 12px;
		background: #fff;
		.cust_title {
			font-weight: 500;
			color: #333;
			font-size: 34px;
			line-height: 48px;
		}
		.cust_tips {
			padding: 24px 0 10px;
			font-size: 24px;
			line-height: 34px;
			color: #999;
		}
	}
	.auth_manager {
		margin: 20px 0 0;
		padding: 0 30px 30px;
		border-radius: 12px;
		background: #fff;
		.manager_title {
			padding: 30px 0 0;
			font-weight: 500;
			color: #333;
			font-size: 34px;
			line-height: 48px;
		}
		.auth_sms {
			.sms_btn {
				line-height: 42px;
				font-size: 30px;
				color: #ed3636;
				&.disabled {
					color: #999;
				}
			}
			.sms_time {
				line-height: 42px;
				font-size: 30px;
				color: #666;
				i {
					color: #ed3636;
				}
			}
		}
	}
	.btn_auth {
		margin: 48px 0 0;
		border-radius: 12px;
	}
	.btn_list {
		margin: 24px 0 0;
		background: transparent;
		border-radius: 12px;
	}
}
</style>

<style lang="less">
.__auth_dialog__ {
	.van-dialog__header {
		padding-top: 48px;
		color: #333;
		font-size: 34px;
		line-height: 48px;
	}
	.van-dialog__message {
		color: #999;
		font-size: 30px;
		line-height: 44px;
		padding: 40px;
		padding-top: 24px;
	}
	.van-button {
		height: 92px;
		font-size: 32px;
	}
}
</style>
